<template>
  <div class="search-container">
     <van-nav-bar
  title="搜索中心"
  left-arrow
  @click-left="$router.go(-1)"
/>
<van-search
  v-model="value"
  show-action
  placeholder="请输入搜索关键词"
  autofocus
  shape="round"
  @search="onSearch"
  @input="onInput"
>
  <template #action>
    <div @click="onSearch">搜索</div>
  </template>
</van-search>



<van-cell-group>
<van-cell v-for="(item,index) in showList" :key="index"  icon="search" @click="$router.push({path:'/searchResult',query:{q:suggestionList[index]}})" >
 <template #title>
    <span class="custom-title" v-html="item"></span>
  </template>
  </van-cell>
</van-cell-group>
  </div>
</template>

<script>
import {getSuggestion} from '@/views/home/home.js'
export default {
name:'search',
data() {
    return {
        value: '',
        suggestionList:[],
        timeID:null
    };
},
methods: {
    onSearch(){
        console.log(this.value);
    this.$router.push({path:'/searchResult',query:{q:this.value}})
    },

    onInput(){
      clearTimeout(this.timeID)
      this.timeID=setTimeout(async() => {
         console.log(this.value);
        if(this.value==''){
            this.suggestionList=[]
            return
        }
        // console.log(11);
        let res=await getSuggestion(this.value)
        console.log(res);
        this.suggestionList=res.data.data.options
      }, 500);
      
    },

},
computed:{
    showList(){
        return this.suggestionList.map(value=>{
            let reg=new RegExp(this.value,'ig')
            return value.replace(reg,
            match=>`<span style="color:red">${match}</span>`
            );
        })
    }
}
}
</script>

<style>

</style>